package pub.cleangao.codegen.enquiry.sqlserver;

import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.enquiry.ColumnEnquiry;
import pub.cleangao.codegen.enquiry.TableEnquiry;
import pub.cleangao.codegen.enquiry.TableInfo;
import pub.cleangao.codegen.util.ClassField;
import java.util.Map;



public class SqlServerTableEnquiry extends TableEnquiry {

    public SqlServerTableEnquiry(GenConfigHolder config, ColumnEnquiry columnEnquiry) {
        super(config, columnEnquiry);
    }

    @Override
    public String getShowTablesSql() {
        return "SELECT SS.name + '.' + t.name AS table_name " +
                ",CONVERT(varchar(50),ISNULL(ext.value, '')) as comment " +
                "FROM sysobjects t " +
                "INNER JOIN sys.objects SO ON t.name = SO.name " +
                "INNER JOIN sys.schemas  SS ON SO.schema_id = SS.schema_id " +
                "LEFT JOIN sys.extended_properties ext ON ext.major_id = SO.object_id and ext.minor_id=0 " +
                "WHERE t.xtype='u' " +
                this.buildTableSchWhere() +
                " ORDER BY SS.name ASC,t.name ASC";
    }

    private String buildTableSchWhere() {
        if (this.schemaTables != null && this.schemaTables.size() > 0) {
            int i = 0;
            StringBuilder tables = new StringBuilder(" and ( ");
            for (String table : this.schemaTables) {
                String[] tableArr = table.split("\\.");
                if (i > 0) {
                    tables.append(" or ");
                }
                tables.append("(SS.name='").append(tableArr[0]).append("' and t.name='").append(tableArr[1]).append("') ");
                i++;
            }
            tables.append(" )");
            return tables.toString();
        }
        return "";
    }

    @Override
    public TableInfo buildTableInfo(Map<String, Object> tableMap) {
        TableInfo tableInfo = new TableInfo();
        tableInfo.setTableName(ClassField.convertString(tableMap.get("TABLE_NAME")));
        tableInfo.setTableNameHyphen(tableInfo.getTableName().replace("_", "-"));
        tableInfo.setComment(ClassField.convertString(tableMap.get("COMMENT")));
        return tableInfo;
    }


}
